package com.jay.bookkeep.ui
import android.graphics.Color
import android.graphics.Matrix
import android.os.Bundle
import android.view.View
import com.amap.api.location.AMapLocation
import com.app.baselibrary.base.BaseViewModelActivity
import com.app.baselibrary.utils.LogUtil
import com.app.baselibrary.utils.PermissionUtils
import com.app.baselibrary.utils.StringUtil
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.jay.bookkeep.MyApplication
import com.jay.bookkeep.bean.Data
import com.jay.bookkeep.databinding.ActivityWeatherBinding
import com.jay.bookkeep.utils.listener.LocationResultListener
import com.jay.bookkeep.utils.listener.MapLocationListener
import com.jay.bookkeep.view.CustomXAxisFormatter
import com.jay.bookkeep.view.LineValueFormatter
import com.jay.bookkeep.vm.WeatherViewModel

/**
 * 天气预报
 */
class WeatherActivity: BaseViewModelActivity<ActivityWeatherBinding,WeatherViewModel>(), LocationResultListener {

    private var weatherData:List<Data>?=null
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        linechart=requireViewBinding().lyLineChart
        linechart!!.setNoDataText("没有数据")//没有数据时显示的文字
        linechart!!.setNoDataTextColor(Color.WHITE)//没有数据时显示文字的颜色
        if(MyApplication.getMyMapLocation()!=null){
            getHttpData()
        }else{
            showPerDialog()
        }
        initData()
    }

    //图表
    private var linechart: LineChart? = null
    private fun  initLineChat(){
        linechart!!.setDrawGridBackground(false)
        linechart!!.description.isEnabled = false
        linechart!!.setTouchEnabled(true)
        linechart!!.isDragEnabled = true //平移
        linechart!!.setScaleEnabled(false)//缩放
        linechart!!.setPinchZoom(false)
        chatData()
    }
    private var minValue = -10f//y轴上最小的值
    private var maxValue = 10f//y轴上最大的值
    private fun chatData() {
        val mList= java.util.ArrayList<String>()
        val minList= java.util.ArrayList<Float>()
        val maxList= java.util.ArrayList<Float>()
        if(weatherData!=null&&weatherData!!.isNotEmpty()){
            weatherData!!.forEachIndexed { _, weather ->
                mList.add(weather.riqi)
                val wenDu=weather.wendu.split("～")
                if (wenDu[0].toFloat() > minValue) {
                    minValue =wenDu[0].toFloat()
                }
                if (wenDu[1].toFloat() > maxValue) {
                    maxValue =wenDu[1].toFloat()
                }
                minList.add(wenDu[0].toFloat())
                maxList.add(wenDu[1].toFloat())

            }
        }
        initXYChart(mList)
        setChatData(maxList,minList)
    }
    private fun  initData(){
     val todayWeek=StringUtil.getToDayWeek()
     requireViewBinding().tvWeek.text=todayWeek
     requireViewModel().mWeatherDataEntity.observerNotNull {
         weatherData=it.data
         weatherData!!.forEachIndexed { _, data ->
             if(data.riqi==todayWeek){
                 requireViewBinding().tvTemperature.text=data.wendu
             }
         }
         initLineChat()
     }
    }
    private fun showPerDialog(){
        PermissionUtils.getInstance().requsetLocationPermission(this,object :
            PermissionUtils.ActivityResultData{
            override fun onDataesult(code: Int){
                if(code==200){
                    //进行定位
                    MapLocationListener.getInstance().setLocationResultListener(this@WeatherActivity)
                    MapLocationListener.getInstance().startLocation()
                }
            }
        })

    }
    override fun callBackLocation(location: AMapLocation?, code: Int) {
        if (code == 0) {
            //定位成功
            MyApplication.setMyMapLocation(location!!)
            MapLocationListener.getInstance().stopLocation()
            getHttpData()
        }else{
            //定位失败
            LogUtil.logE("定位失败了----------")
        }
    }

    private fun getHttpData(){
        val mLocation=MyApplication.getMyMapLocation()
        requireViewModel().getWeather(mLocation!!.district)
        requireViewBinding().tvCity.text=mLocation!!.district
    }



    /**
     * 初始化xy轴
     */
    private fun initXYChart(list: List<String>) {
        val l: Legend = linechart!!.legend
        l.form = Legend.LegendForm.NONE
        l.textSize = 12f
        //X轴设置
        val xl: XAxis = linechart!!.xAxis
        xl.setAvoidFirstLastClipping(true)
        xl.axisMinimum = 0f
        xl.textColor = Color.parseColor("#FFFFFF")
       //间隔1
        xl.granularity = 1f
        xl.textSize=12f
        xl.position = XAxis.XAxisPosition.BOTTOM
        xl.axisLineColor = Color.parseColor("#EBEBEB")
        xl.axisMaximum = 5.5f//设置最小值
        xl.axisMinimum = -0.5f//设置最大值
        xl.setLabelCount(list.size, true)
        //禁用网格
        xl.setDrawGridLines(false)
        xl.valueFormatter = CustomXAxisFormatter(list as ArrayList<String>)

        //Y轴设置
        val leftAxis: YAxis = linechart!!.axisLeft
        leftAxis.isInverted = false
        leftAxis.textSize=10f
        leftAxis.textColor = Color.parseColor("#FFFFFF")
        leftAxis.axisLineWidth = 1f
        if(minValue<0){
            leftAxis.axisMinimum =minValue+-10f
        }else{
            leftAxis.axisMinimum =minValue-10f
        }
       if(maxValue<0){
           leftAxis.axisMaximum =maxValue-10f
       }else{
           leftAxis.axisMaximum =maxValue+10f
       }

        leftAxis.setDrawAxisLine(true)//是否绘制轴线
        //设置网格线为虚线效果 10f是虚线的长度，5f是虚线之间的间隔，0是以何种角度绘制虚线
        leftAxis.enableGridDashedLine(10f, 5f, 0f)
        leftAxis.gridColor = Color.parseColor("#EBEBEB")
        //是否绘制0所在的网格线
        leftAxis.setDrawZeroLine(false)
        val rightAxis: YAxis = linechart!!.axisRight
        //设置图表右边的y轴禁用
        rightAxis.isEnabled = false
    }

    /**
      * 先将缩放比设置成0后，再去设置你想要的缩放比。
      * 若不这样做的话，在当前页面重新加载数据时，你所设置的缩放比会失效
     */
    private fun setMoveData() {
        linechart!!.moveViewToX(0f)
        linechart!!.setScaleMinima(1.0f, 1.0f)
        linechart!!.viewPortHandler.refresh(Matrix(), linechart!!, true)
    }
    /**
     * 设置数据
     */
    private fun setChatData(list1: List<Float>,list2:List<Float>) {
        if (list1.isNotEmpty()) {
            val values1 = java.util.ArrayList<Entry>()
            val values2 = java.util.ArrayList<Entry>()
            //圆圈颜色
            val values2Circle = java.util.ArrayList<Int>()
            for (i in list1.indices) {
                values1.add(Entry(i.toFloat(), list1[i].toFloat()))
            }
            for (i in list2.indices) {
                values2.add(Entry(i.toFloat(), list2[i].toFloat()))
                if(list2[i]>0){
                    values2Circle.add(Color.WHITE)
                }else{
                    values2Circle.add(Color.BLACK)
                }
            }
            var set1= LineDataSet(values1, "")
            set1.axisDependency = YAxis.AxisDependency.LEFT
            //线的颜色
            set1.color = Color.parseColor("#FF0000")
            set1.lineWidth = 1f
            // 是否显示每个点的y值
            set1.setDrawValues(true)
            set1.setDrawCircles(true)
            set1.setCircleColor(Color.WHITE)
            // 设置曲线为圆滑曲线
            set1.mode = LineDataSet.Mode.CUBIC_BEZIER
            // 显示定位线
            set1.isHighlightEnabled = false
            //设置禁用范围背景填充
            set1.setDrawFilled(false)
//            set1.valueTextSize=14f
//            set1.valueTextColor=Color.parseColor("#FF0000")
            set1.valueFormatter=LineValueFormatter(list1)

            var set2= LineDataSet(values2, "")
            set2.axisDependency = YAxis.AxisDependency.LEFT
            set2.color = Color.parseColor("#FFCD0000")
            set2.lineWidth = 1f
            set2.setDrawValues(true)
            set2.setDrawCircles(true)
            set2.circleColors = values2Circle
            set2.mode = LineDataSet.Mode.LINEAR
            // 设置虚线样式
            set2.enableDashedLine(10f, 5f, 0f)
            // 设置高亮线为虚线
//            set2.enableDashedHighlightLine(10f, 5f, 0f);
            // 显示定位线
            set2.isHighlightEnabled = false
            set2.setDrawFilled(false)//设置禁用范围背景填充

            val data = LineData(set1,set2)
            data.setValueTextColor(Color.WHITE)
            data.setValueTextSize(10f)
            setMoveData()
            linechart!!.data = data
            linechart!!.visibility = View.VISIBLE
            linechart!!.setVisibleXRangeMaximum(100f)//设置屏幕显示条数
            linechart!!.invalidate()
        } else {
            val values1 =java.util.ArrayList<Entry>()
            var set1= LineDataSet(values1, "")
            // 不显示定位线
            set1.isHighlightEnabled = false
            val data = LineData(set1)
            setMoveData()
            linechart!!.data = data
            linechart!!.visibility = View.VISIBLE
            linechart!!.setVisibleXRangeMaximum(100f)//设置屏幕显示条数
            linechart!!.invalidate()
        }
    }
    /**
     * // 创建数据集
     * LineDataSet lineDataSet = new LineDataSet(data, "虚线数据集");
     *
     * // 设置虚线样式
     * DashPathEffect dashPathEffect = new DashPathEffect(new float[]{10f, 10f}, 0f);
     * lineDataSet.enableDashedLine(10f, 5f, 0f);
     * lineDataSet.setLineDashPathEffect(dashPathEffect);
     *
     * // 设置其他样式
     * lineDataSet.setColor(Color.BLUE); // 线条颜色
     * lineDataSet.setDrawCircleHole(false); // 不绘制圆圈中心
     * lineDataSet.setDrawValues(false); // 不在数据点处显示值
     * lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线
     *
     * // 添加数据集到图表
     * LineData lineData = new LineData(dataSets);
     * lineChart.setData(lineData);
     */
}